/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package ru.ibrae.mchs.radiation.entities.controllers;

import ru.ibrae.mchs.radiation.entities.Comment;
import ru.ibrae.mchs.radiation.entities.controllers.exceptions.NonexistentEntityException;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.Query;
import javax.persistence.EntityNotFoundException;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import ru.ibrae.mchs.radiation.entities.Geoobject;
import java.util.HashSet;
import java.util.Set;

/**
 *
 * @author murr
 */
public class CommentJpaController {

    public CommentJpaController() {
        emf = Persistence.createEntityManagerFactory("DesktopApplication4PU");
    }
    private EntityManagerFactory emf = null;

    public EntityManager getEntityManager() {
        return emf.createEntityManager();
    }

    public void create(Comment comment) {
        if (comment.getGeoobjectSet() == null) {
            comment.setGeoobjectSet(new HashSet<Geoobject>());
        }
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            Set<Geoobject> attachedGeoobjectSet = new HashSet<Geoobject>();
            for (Geoobject geoobjectSetGeoobjectToAttach : comment.getGeoobjectSet()) {
                geoobjectSetGeoobjectToAttach = em.getReference(geoobjectSetGeoobjectToAttach.getClass(), geoobjectSetGeoobjectToAttach.getIdNp());
                attachedGeoobjectSet.add(geoobjectSetGeoobjectToAttach);
            }
            comment.setGeoobjectSet(attachedGeoobjectSet);
            em.persist(comment);
            for (Geoobject geoobjectSetGeoobject : comment.getGeoobjectSet()) {
                Comment oldCommentOfGeoobjectSetGeoobject = geoobjectSetGeoobject.getComment();
                geoobjectSetGeoobject.setComment(comment);
                geoobjectSetGeoobject = em.merge(geoobjectSetGeoobject);
                if (oldCommentOfGeoobjectSetGeoobject != null) {
                    oldCommentOfGeoobjectSetGeoobject.getGeoobjectSet().remove(geoobjectSetGeoobject);
                    oldCommentOfGeoobjectSetGeoobject = em.merge(oldCommentOfGeoobjectSetGeoobject);
                }
            }
            em.getTransaction().commit();
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void edit(Comment comment) throws NonexistentEntityException, Exception {
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            Comment persistentComment = em.find(Comment.class, comment.getIdComent());
            Set<Geoobject> geoobjectSetOld = persistentComment.getGeoobjectSet();
            Set<Geoobject> geoobjectSetNew = comment.getGeoobjectSet();
            Set<Geoobject> attachedGeoobjectSetNew = new HashSet<Geoobject>();
            for (Geoobject geoobjectSetNewGeoobjectToAttach : geoobjectSetNew) {
                geoobjectSetNewGeoobjectToAttach = em.getReference(geoobjectSetNewGeoobjectToAttach.getClass(), geoobjectSetNewGeoobjectToAttach.getIdNp());
                attachedGeoobjectSetNew.add(geoobjectSetNewGeoobjectToAttach);
            }
            geoobjectSetNew = attachedGeoobjectSetNew;
            comment.setGeoobjectSet(geoobjectSetNew);
            comment = em.merge(comment);
            for (Geoobject geoobjectSetOldGeoobject : geoobjectSetOld) {
                if (!geoobjectSetNew.contains(geoobjectSetOldGeoobject)) {
                    geoobjectSetOldGeoobject.setComment(null);
                    geoobjectSetOldGeoobject = em.merge(geoobjectSetOldGeoobject);
                }
            }
            for (Geoobject geoobjectSetNewGeoobject : geoobjectSetNew) {
                if (!geoobjectSetOld.contains(geoobjectSetNewGeoobject)) {
                    Comment oldCommentOfGeoobjectSetNewGeoobject = geoobjectSetNewGeoobject.getComment();
                    geoobjectSetNewGeoobject.setComment(comment);
                    geoobjectSetNewGeoobject = em.merge(geoobjectSetNewGeoobject);
                    if (oldCommentOfGeoobjectSetNewGeoobject != null && !oldCommentOfGeoobjectSetNewGeoobject.equals(comment)) {
                        oldCommentOfGeoobjectSetNewGeoobject.getGeoobjectSet().remove(geoobjectSetNewGeoobject);
                        oldCommentOfGeoobjectSetNewGeoobject = em.merge(oldCommentOfGeoobjectSetNewGeoobject);
                    }
                }
            }
            em.getTransaction().commit();
        } catch (Exception ex) {
            String msg = ex.getLocalizedMessage();
            if (msg == null || msg.length() == 0) {
                Integer id = comment.getIdComent();
                if (findComment(id) == null) {
                    throw new NonexistentEntityException("The comment with id " + id + " no longer exists.");
                }
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void destroy(Integer id) throws NonexistentEntityException {
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            Comment comment;
            try {
                comment = em.getReference(Comment.class, id);
                comment.getIdComent();
            } catch (EntityNotFoundException enfe) {
                throw new NonexistentEntityException("The comment with id " + id + " no longer exists.", enfe);
            }
            Set<Geoobject> geoobjectSet = comment.getGeoobjectSet();
            for (Geoobject geoobjectSetGeoobject : geoobjectSet) {
                geoobjectSetGeoobject.setComment(null);
                geoobjectSetGeoobject = em.merge(geoobjectSetGeoobject);
            }
            em.remove(comment);
            em.getTransaction().commit();
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public List<Comment> findCommentEntities() {
        return findCommentEntities(true, -1, -1);
    }

    public List<Comment> findCommentEntities(int maxResults, int firstResult) {
        return findCommentEntities(false, maxResults, firstResult);
    }

    private List<Comment> findCommentEntities(boolean all, int maxResults, int firstResult) {
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            cq.select(cq.from(Comment.class));
            Query q = em.createQuery(cq);
            if (!all) {
                q.setMaxResults(maxResults);
                q.setFirstResult(firstResult);
            }
            return q.getResultList();
        } finally {
            em.close();
        }
    }

    public Comment findComment(Integer id) {
        EntityManager em = getEntityManager();
        try {
            return em.find(Comment.class, id);
        } finally {
            em.close();
        }
    }

    public int getCommentCount() {
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            Root<Comment> rt = cq.from(Comment.class);
            cq.select(em.getCriteriaBuilder().count(rt));
            Query q = em.createQuery(cq);
            return ((Long) q.getSingleResult()).intValue();
        } finally {
            em.close();
        }
    }

}
